/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.db_vdumper.servicesimpl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.opu.db_vdumper.beans.ColumnBean;
import org.opu.db_vdumper.beans.TableBean;
import org.opu.db_vdumper.domain.DColumn;
import org.opu.db_vdumper.domain.DColumnRelation;
import org.opu.db_vdumper.domain.DTable;
import org.opu.db_vdumper.services.BeanService;
import org.opu.db_vdumper.util.Logger;

/**
 *
 * @author yura
 */
public class BeanServiceImpl implements BeanService {

    @Override
    public List<TableBean> getTables(Map<String, DTable> tables,
            Map<DTable, Map<String, DColumn>> columns) {

        List<TableBean> tableBeans = new ArrayList<TableBean>();
        Map<String, ColumnBean> mapedCols = new HashMap<String, ColumnBean>();

        for (DTable t : tables.values()) {
            TableBean tblb = new TableBean(t.getName(), t.getSchema());
            Collection<DColumn> cols = columns.get(t).values();

            for (DColumn c : cols) {
                ColumnBean cb = new ColumnBean(c.getName(), c.getTypeName(),
                        tblb);
                tblb.add(cb);
                mapedCols.put(tblb.getSchema() + "." + tblb.getName() + "."
                        + c.getName(), cb);
            }

            tableBeans.add(tblb);
        }

        for (DTable t : tables.values()) {
            List<DColumnRelation> relations = t.getRelations();
            for (DColumnRelation r : relations) {

                DColumn f = r.getFrom();
                DTable tbl = f.getTable();

                ColumnBean from = mapedCols.get(tbl.getSchema() + "."
                        + tbl.getName() + "." + f.getName());
                ColumnBean to = mapedCols.get(r.getToTblSchem() + "."
                        + r.getToTblName() + "." + r.getToColumnName());

                from.setReferences(to);
                Logger.getInstance().debug(this, "add relation: to <"
                        + tbl.getSchema() + "." + tbl.getName() + "."
                        + f.getName() + "> on <" + r.getToTblSchem() + "."
                        + r.getToTblName() + "." + r.getToColumnName() + ">");
            }
        }

        return tableBeans;
    }
}
